const app = getApp();

Page({
  data: {
    sessions: [], // 会话列表
    currentSession: null, // 当前选中的会话
    messages: [], // 当前会话的消息列表
    inputText: '', // 输入框内容
    isLoading: false,
    showSessionList: true, // 是否显示会话列表
    unreadCount: 0, // 未读消息数量
    userInfo: {}, // 当前用户信息
    riderInfo: {}, // 骑手信息
    page: 1,
    hasMore: true,
    showAttachmentBar: false, // 是否显示附件选择栏
    refreshTimer: null, // 定时刷新器
    showCloseDialog: false, // 是否显示关闭对话框
    scrollIntoView: '' // 滚动到指定元素
  },

  onLoad() {
    this.checkLoginStatus();
    this.loadRiderInfo();
  },

  onShow() {
    this.checkLoginStatus();
    if (this.data.isLoggedIn) {
      this.loadSessions();
      this.getUnreadCount();
      this.startAutoRefresh(); // 启动自动刷新
    }
  },

  onHide() {
    try {
      this.stopAutoRefresh(); // 停止自动刷新
    } catch (error) {
      console.error('onHide error:', error);
    }
  },

  onUnload() {
    try {
      this.stopAutoRefresh(); // 停止自动刷新
    } catch (error) {
      console.error('onUnload error:', error);
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    if (!token || !riderId) {
      this.setData({ isLoggedIn: false });
      return;
    }

    this.setData({
      isLoggedIn: true,
      riderId: riderId
    });
  },

  // 加载骑手信息
  loadRiderInfo() {
    // 从本地存储获取骑手信息
    const riderName = wx.getStorageSync('riderName') || '';
    const riderPhone = wx.getStorageSync('riderPhone') || '';

    this.setData({
      riderInfo: {
        name: riderName,
        phone: riderPhone
      }
    });
  },

  // 加载会话列表
  loadSessions() {
    if (this.data.isLoading) return;
    
    this.setData({ isLoading: true });
    
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    wx.request({
      url: `${ip}/api/customer-service/session/list-by-type`,
      method: 'GET',
      data: {
        receiverType: 3, // 3-骑手
      },
      header: {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          const sessions = res.data.data || [];

          this.setData({
            sessions: sessions,
            isLoading: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '获取会话失败',
            icon: 'none'
          });
          this.setData({ isLoading: false });
        }
      },
      fail: (error) => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ isLoading: false });
      }
    });
  },

  // 启动自动刷新
  startAutoRefresh() {
    // 先清除之前的定时器
    this.stopAutoRefresh();

    const timer = setInterval(() => {
      try {
        // 检查页面是否还存在
        if (!this || !this.data) return;

        if (this.data.isLoggedIn) {
          // 检查方法是否存在
          if (typeof this.getUnreadCount === 'function') {
            this.getUnreadCount(); // 刷新未读消息数量
          }

          // 如果在会话列表页面，刷新会话列表
          if (this.data.showSessionList && typeof this.loadSessions === 'function') {
            this.loadSessions();
          }

          // 如果在聊天页面，刷新消息
          if (this.data.currentSession && !this.data.showSessionList && typeof this.loadMessages === 'function') {
            this.loadMessages(this.data.currentSession.sessionId);
          }
        }
      } catch (error) {
        console.error('定时刷新出错:', error);
        // 如果出错，停止定时器
        this.stopAutoRefresh();
      }
    }, 30000); // 30秒刷新一次

    this.setData({
      refreshTimer: timer
    });
  },

  // 停止自动刷新
  stopAutoRefresh() {
    try {
      if (this.data && this.data.refreshTimer) {
        clearInterval(this.data.refreshTimer);
        this.setData({
          refreshTimer: null
        });
      }
    } catch (error) {
      console.error('停止自动刷新出错:', error);
    }
  },

  // 获取未读消息数量 - 优化版本
  getUnreadCount() {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    if (!token || !riderId) {
      return;
    }

    wx.request({
      url: `${ip}/api/customer-service/message/unread-count`,
      method: 'GET',
      data: {
        userType: 3, // 3-骑手
        userId: riderId
      },
      header: {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          const unreadCount = res.data.data || 0;

          this.setData({
            unreadCount: unreadCount
          });
        } else {
          this.setData({
            unreadCount: 0
          });
        }
      },
      fail: (error) => {
        this.setData({
          unreadCount: 0
        });
      }
    });
  },

  // 选择会话
  selectSession(e) {
    const sessionId = e.currentTarget.dataset.sessionId;
    const session = this.data.sessions.find(s => s.sessionId === sessionId);

    if (!session) return;

    this.setData({
      currentSession: session,
      showSessionList: false,
      messages: [],
      page: 1,
      hasMore: true
    });

    // 直接加载消息，从消息中获取发送者信息
    this.loadMessages(sessionId);
    this.markAsRead(sessionId);
  },

  // 加载消息列表
  loadMessages(sessionId, page = 1) {
    // 保存this上下文
    const self = this;

    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;

    wx.request({
      url: `${ip}/api/customer-service/session/${sessionId}/messages`,
      method: 'GET',
      data: {
        page: page,
        size: 50
      },
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        try {
          // 检查页面是否还存在
          if (!self || !self.data) return;
          if (res.data.code === 200) {
            const newMessages = res.data.data || [];

            // 从消息中提取用户信息并更新会话
            if (newMessages.length > 0) {
              self.updateSessionFromMessages(newMessages);
            }

            let finalMessages;
            if (page === 1) {
              // 第一页或刷新时，去重处理
              const existingMessages = self.data.messages || [];
              const existingIds = new Set(existingMessages.map(msg => msg.id));

              // 只添加不存在的新消息
              const uniqueNewMessages = newMessages.filter(msg => !existingIds.has(msg.id));

              // 如果是自动刷新且没有新消息，保持原有消息列表
              if (uniqueNewMessages.length === 0 && existingMessages.length > 0) {
                finalMessages = existingMessages.map(msg => ({ ...msg, isNew: false }));
              } else {
                // 标记新消息
                const markedNewMessages = uniqueNewMessages.map(msg => ({ ...msg, isNew: true }));
                const markedExistingMessages = existingMessages.map(msg => ({ ...msg, isNew: false }));

                // 合并消息并按时间排序
                finalMessages = [...markedExistingMessages, ...markedNewMessages].sort((a, b) => {
                const timeA = new Date(a.createTime || a.createTimeFormatted);
                const timeB = new Date(b.createTime || b.createTimeFormatted);
                return timeA - timeB;
              });

              // 3秒后移除新消息标识
              setTimeout(() => {
                if (self && self.data) {
                  const updatedMessages = self.data.messages.map(msg => ({ ...msg, isNew: false }));
                  self.setData({ messages: updatedMessages });
                }
              }, 3000);
            }
          } else {
            // 分页加载时，添加到现有消息前面
            finalMessages = [...newMessages, ...self.data.messages].map(msg => ({ ...msg, isNew: false }));
          }

          // 处理图片URL，确保是完整的URL
          finalMessages = finalMessages.map(msg => {
            if (msg.messageType == 2 && msg.content) {
              // 如果是相对路径，拼接完整URL
              if (!msg.content.startsWith('http')) {
                const ip = app.globalData.userIPInfo;
                msg.content = `${ip}${msg.content.startsWith('/') ? '' : '/'}${msg.content}`;
              }
            }
            return msg;
          });

          self.setData({
            messages: finalMessages,
            hasMore: newMessages.length === 50
          });

          // 滚动到底部（新消息）
          if (page === 1) {
            self.scrollToBottom();
          }
        }
        } catch (error) {
          console.error('loadMessages success处理出错:', error);
        }
      },
      fail: (error) => {
        // 静默处理错误
      }
    });
  },

  // 从消息中更新会话信息
  updateSessionFromMessages(messages) {
    try {
      if (!this || !this.data || !messages || messages.length === 0) return;

    // 找到用户发送的消息（非骑手消息）
    const userMessage = messages.find(msg => msg.senderType !== 3);
    // 找到骑手发送的消息
    const riderMessage = messages.find(msg => msg.senderType === 3);

    // 更新当前会话信息
    const currentSession = this.data.currentSession;
    const updatedSession = {
      ...currentSession
    };

    // 从用户消息中获取用户信息
    if (userMessage) {
      updatedSession.userName = userMessage.senderName;
      updatedSession.userType = userMessage.senderType;
      updatedSession.userId = userMessage.senderId;
      updatedSession.targetUserType = userMessage.senderType;
      updatedSession.targetUserId = userMessage.senderId;
      updatedSession.targetName = userMessage.senderName;
    }

    // 从骑手消息中获取接收者（用户）信息
    if (riderMessage && !userMessage) {
      updatedSession.userName = riderMessage.receiverName;
      updatedSession.userType = riderMessage.receiverType;
      updatedSession.userId = riderMessage.receiverId;
      updatedSession.targetUserType = riderMessage.receiverType;
      updatedSession.targetUserId = riderMessage.receiverId;
      updatedSession.targetName = riderMessage.receiverName;
    }

      this.setData({
        currentSession: updatedSession
      });
    } catch (error) {
      console.error('updateSessionFromMessages出错:', error);
    }
  },

  // 发送消息
  sendMessage() {
    const content = this.data.inputText.trim();
    if (!content || !this.data.currentSession) return;

    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;
    const session = this.data.currentSession;
    // 使用会话详情中的准确用户信息
    const receiverType = session.targetUserType || session.userType || session.targetType;
    const receiverId = session.targetUserId || session.userId || session.targetId;

    wx.request({
      url: `${ip}/api/customer-service/message/send`,
      method: 'POST',
      data: {
        sessionId: session.sessionId,
        senderType: 3, // 3-骑手
        senderId: riderId,
        receiverType: receiverType, // 使用准确的用户类型
        receiverId: receiverId, // 使用准确的用户ID
        messageType: 1, // 1-文本消息
        content: content
      },
      header: {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 清空输入框
          this.setData({ inputText: '' });

          // 重新加载消息
          this.loadMessages(session.sessionId);
        } else {
          wx.showToast({
            title: res.data.message || '发送失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.showToast({
          title: '发送失败',
          icon: 'none'
        });
      }
    });
  },

  // 标记消息为已读
  markAsRead(sessionId) {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    wx.request({
      url: `${ip}/api/customer-service/message/read`,
      method: 'POST',
      data: {
        sessionId: sessionId,
        receiverType: 3, // 3-骑手
        receiverId: riderId
      },
      header: {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 更新未读数量
          this.getUnreadCount();
        }
      }
    });
  },

  // 输入框内容变化
  onInputChange(e) {
    this.setData({
      inputText: e.detail.value
    });
  },

  // 返回会话列表
  backToSessionList() {
    this.setData({
      showSessionList: true,
      currentSession: null,
      messages: [],
      showCloseDialog: false // 重置对话框状态
    });
  },

  // 显示关闭对话框
  showCloseDialog() {
    this.setData({
      showCloseDialog: true
    });
  },

  // 隐藏关闭对话框
  hideCloseDialog() {
    this.setData({
      showCloseDialog: false
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },



  // 确认关闭会话
  confirmCloseSession() {
    // 隐藏对话框
    this.setData({
      showCloseDialog: false
    });

    if (!this.data.currentSession) {
      wx.showToast({
        title: '没有当前会话',
        icon: 'none'
      });
      return;
    }

    wx.showToast({
      title: '会话已关闭',
      icon: 'success',
      duration: 1000
    });

    // 关闭会话
    this.closeSession(this.data.currentSession.sessionId);
  },

  // 滚动到底部
  scrollToBottom() {
    wx.nextTick(() => {
      // 使用scroll-into-view滚动到底部
      this.setData({
        scrollIntoView: 'message-bottom'
      });

      // 清除scrollIntoView，避免影响后续滚动
      setTimeout(() => {
        this.setData({
          scrollIntoView: ''
        });
      }, 500);
    });
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '';

    try {
      let date;

      // 如果是已格式化的时间字符串，直接返回简化版本
      if (typeof timestamp === 'string' && timestamp.includes('-')) {
        // 格式如 "2025-06-24 10:24:48"
        date = new Date(timestamp);
      } else {
        // 如果是时间戳（秒或毫秒）
        const ts = parseInt(timestamp);
        if (ts.toString().length === 10) {
          // 10位时间戳，秒级
          date = new Date(ts * 1000);
        } else {
          // 13位时间戳，毫秒级
          date = new Date(ts);
        }
      }

      if (isNaN(date.getTime())) {
        return timestamp; // 如果解析失败，返回原始值
      }

      const now = new Date();
      const diff = now - date;

      if (diff < 60000) { // 1分钟内
        return '刚刚';
      } else if (diff < 3600000) { // 1小时内
        return Math.floor(diff / 60000) + '分钟前';
      } else if (diff < 86400000) { // 24小时内
        return Math.floor(diff / 3600000) + '小时前';
      } else {
        // 格式化为 MM-DD HH:mm
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `${month}-${day} ${hours}:${minutes}`;
      }
    } catch (error) {
      return timestamp || '';
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadSessions();
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多消息
  onReachTop() {
    if (this.data.currentSession && this.data.hasMore) {
      this.setData({
        page: this.data.page + 1
      });
      this.loadMessages(this.data.currentSession.sessionId, this.data.page);
    }
  },

  // 跳转到登录页面
  goToLogin() {
    wx.navigateTo({
      url: '/pages/index/index'
    });
  },

  // 根据订单创建客服会话
  createSessionByOrder(orderSn) {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;

    wx.request({
      url: `${ip}/api/customer-service/session/create-by-order`,
      method: 'POST',
      data: {
        orderSn: orderSn
      },
      header: {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        if (res.data.code === 200) {
          const session = res.data.data;

          // 添加到会话列表
          const sessions = [session, ...this.data.sessions];
          this.setData({ sessions });

          // 直接进入该会话
          this.setData({
            currentSession: session,
            showSessionList: false,
            messages: [],
            page: 1,
            hasMore: true
          });

          // 直接加载消息，从消息中获取用户信息
          this.loadMessages(session.sessionId);
        } else {
          wx.showToast({
            title: res.data.message || '创建会话失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.showToast({
          title: '创建会话失败',
          icon: 'none'
        });
      }
    });
  },

  // 获取用户信息
  getUserInfo(userType, userId) {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;

    return new Promise((resolve, reject) => {
      wx.request({
        url: `${ip}/api/customer-service/user-info`,
        method: 'GET',
        data: {
          userType: userType,
          userId: userId
        },
        header: {
          'Authorization': 'Bearer ' + token
        },
        success: (res) => {
          if (res.data.code === 200) {
            resolve(res.data.data);
          } else {
            reject(res.data.message);
          }
        },
        fail: reject
      });
    });
  },

  // 图片预览
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    if (!url) {
      wx.showToast({
        title: '图片地址无效',
        icon: 'none'
      });
      return;
    }

    wx.previewImage({
      current: url,
      urls: [url],
      fail: (error) => {
        wx.showToast({
          title: '图片预览失败',
          icon: 'none'
        });
      }
    });
  },

  // 图片加载成功
  onImageLoad(e) {
    console.log('图片加载成功:', e.detail);
  },

  // 图片加载失败
  onImageError(e) {
    console.log('图片加载失败:', e.detail);
    wx.showToast({
      title: '图片加载失败',
      icon: 'none'
    });
  },

  // 重试加载图片
  retryLoadImage(e) {
    const message = e.currentTarget.dataset.message;
    console.log('重试加载图片:', message);
    // 可以在这里重新请求图片或刷新消息
    this.loadMessages(this.data.currentSession.sessionId);
  },

  // 文件下载
  downloadFile(e) {
    const url = e.currentTarget.dataset.url;
    wx.showLoading({
      title: '下载中...'
    });

    wx.downloadFile({
      url: url,
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200) {
          wx.openDocument({
            filePath: res.tempFilePath,
            success: () => {
              // 文档打开成功
            },
            fail: (error) => {
              wx.showToast({
                title: '无法打开文件',
                icon: 'none'
              });
            }
          });
        } else {
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        wx.showToast({
          title: '下载失败',
          icon: 'none'
        });
      }
    });
  },

  // 关闭会话
  closeSession(sessionId) {
    if (!sessionId) {
      wx.showToast({
        title: '会话ID无效',
        icon: 'none'
      });
      return;
    }

    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;

    // 执行关闭操作
    this.performCloseSession(sessionId, ip, token);
  },

  // 执行关闭会话的API请求
  performCloseSession(sessionId, ip, token) {
    const url = `${ip}/api/customer-service/session/${sessionId}/close`;

    wx.request({
      url: url,
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '会话已关闭',
            icon: 'success'
          });

          // 返回会话列表并刷新
          this.backToSessionList();
          this.loadSessions();
        } else {
          wx.showToast({
            title: res.data.message || '关闭失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  // 切换附件选择栏
  toggleAttachmentBar() {
    this.setData({
      showAttachmentBar: !this.data.showAttachmentBar
    });
  },

  // 选择图片
  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.uploadImage(tempFilePath); // 使用专门的图片上传方法
      },
      fail: (error) => {
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  // 选择文件
  chooseFile() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: (res) => {
        const tempFilePath = res.tempFiles[0].path;
        const fileName = res.tempFiles[0].name;
        this.uploadFile(tempFilePath, fileName); // 使用文件上传方法
      },
      fail: (error) => {
        wx.showToast({
          title: '选择文件失败',
          icon: 'none'
        });
      }
    });
  },

  // 上传图片并发送消息
  uploadImage(filePath) {
    if (!this.data.currentSession) return;

    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;
    const session = this.data.currentSession;
    const receiverType = session.targetUserType || session.userType || session.targetType;
    const receiverId = session.targetUserId || session.userId || session.targetId;

    wx.showLoading({
      title: '发送图片中...'
    });

    // 使用专门的图片消息发送接口
    wx.uploadFile({
      url: `${ip}/api/customer-service/message/send-image`,
      filePath: filePath,
      name: 'file',
      formData: {
        sessionId: session.sessionId,
        senderType: '3', // 3-骑手
        senderId: riderId.toString(),
        receiverType: receiverType.toString(),
        receiverId: receiverId.toString()
      },
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        wx.hideLoading();

        try {
          const data = JSON.parse(res.data);
          if (data.code === 200) {
            // 发送成功，重新加载消息
            this.loadMessages(session.sessionId);
            // 隐藏附件选择栏
            this.setData({ showAttachmentBar: false });

            wx.showToast({
              title: '图片发送成功',
              icon: 'success'
            });
          } else {
            wx.showToast({
              title: data.message || '图片发送失败',
              icon: 'none'
            });
          }
        } catch (error) {
          wx.showToast({
            title: '图片发送失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        wx.showToast({
          title: '图片发送失败',
          icon: 'none'
        });
      }
    });
  },

  // 上传文件并发送消息
  uploadFile(filePath, fileName = '') {
    if (!this.data.currentSession) return;

    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;
    const session = this.data.currentSession;
    const receiverType = session.targetUserType || session.userType || session.targetType;
    const receiverId = session.targetUserId || session.userId || session.targetId;

    wx.showLoading({
      title: '发送文件中...'
    });

    // 使用文件消息发送接口
    wx.uploadFile({
      url: `${ip}/api/customer-service/message/send-file`,
      filePath: filePath,
      name: 'file',
      formData: {
        sessionId: session.sessionId,
        senderType: '3', // 3-骑手
        senderId: riderId.toString(),
        receiverType: receiverType.toString(),
        receiverId: receiverId.toString()
      },
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        wx.hideLoading();

        try {
          const data = JSON.parse(res.data);
          if (data.code === 200) {
            // 发送成功，重新加载消息
            this.loadMessages(session.sessionId);
            // 隐藏附件选择栏
            this.setData({ showAttachmentBar: false });

            wx.showToast({
              title: '文件发送成功',
              icon: 'success'
            });
          } else {
            wx.showToast({
              title: data.message || '文件发送失败',
              icon: 'none'
            });
          }
        } catch (error) {
          wx.showToast({
            title: '文件发送失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        wx.showToast({
          title: '文件发送失败',
          icon: 'none'
        });
      }
    });
  },

  // 备用方法：分步上传文件（如果需要先上传再发送）
  uploadFileOnly(filePath, type = 'general') {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;

    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${ip}/api/customer-service/upload/file`,
        filePath: filePath,
        name: 'file',
        formData: {
          type: type
        },
        header: {
          'Authorization': 'Bearer ' + token
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.code === 200) {
              resolve(data.data);
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          } catch (error) {
            reject(new Error('上传失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }
});
